using System;
using System.Collections;
using GameFramework.DataTable;
using Unity.VisualScripting;
using UnityEngine;
using UnityGameFramework.Runtime;

namespace LS.UGFUnits
{
    [UnitShortTitle("Data Table Row")]
    [UnitSurtitle("Get")]
    public sealed class GetDataTableRow : DataTableUnit
    {
        [Serialize]
        [Inspectable, UnitHeaderInspectable]
        [TypeFilter(typeof(DataRowBase))]
        public System.Type DataTableType { get; private set; }
        
        [DoNotSerialize]
        [PortLabelHidden]
        public ValueInput Id { get; private set; }
        
        [DoNotSerialize]
        [PortLabelHidden]
        public ValueOutput Data { get; private set; }

        protected override void Definition()
        {
            Id = ValueInput<int>(nameof(Id), 0);
            Data = ValueOutput<DataRowBase>(nameof(Data));
            Requirement(Id, Data);
        }

        protected override ControlOutput In(Flow flow)
        {
            int id = flow.GetValue<int>(Id);
            DataTableBase dataTable = Target?.GetDataTable(DataTableType);
            if (dataTable == null)
            {
                flow.SetValue(Data, null);
                return base.In(flow);
            }
            
            foreach (DataRowBase item in (IEnumerable)dataTable)
            {
                if (item.Id == id)
                {
                    flow.SetValue(Data, item);
                    break;
                }
            }
            
            return null;
        }
    }
}